package com.gjy.elk.sb2.logs.controller;

import com.gjy.elk.sb2.logs.module.User;
import com.gjy.elk.sb2.logs.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-29 20:15:41
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    private final UserRepository repository;

    public UserController(UserRepository repository) {
        this.repository = repository;
    }

    @GetMapping
    public List<User> list() {
        log.info("查询用户列表");
        return repository.findAll();
    }

    @PostMapping
    public User create(@RequestBody User user) {
        log.info("创建用户 username={}", user.getUsername());
        return repository.save(user);
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> get(@PathVariable Long id) {
        log.info("查询单个用户 id={}", id);
        Optional<User> opt = repository.findById(id);
        return opt.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    public ResponseEntity<User> update(@PathVariable Long id, @RequestBody User user) {
        log.info("更新用户 id={}, username={}", id, user.getUsername());
        return repository.findById(id)
                .map(existing -> {
                    existing.setUsername(user.getUsername());
                    existing.setEmail(user.getEmail());
                    repository.save(existing);
                    return ResponseEntity.ok(existing);
                })
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        log.info("删除用户 id={}", id);
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}